import cv2
import numpy as np

#1. 输入图像
image_np = cv2.imread('six_star.jpg')

#2. 灰度化
image_gray = cv2.cvtColor(
    image_np,
    cv2.COLOR_BGR2GRAY
)
# 中值滤波
no_noise_image = cv2.medianBlur(
    image_gray,  # 要滤波的图像
    7  # 核
)

#3. 二值化
_, image_thresh = cv2.threshold(
    no_noise_image,
    50,
    255,
    cv2.THRESH_BINARY
)
# 4. 查找轮廓
contours, hierarchy = cv2.findContours(
    image_thresh,
    cv2.RETR_CCOMP,
    cv2.CHAIN_APPROX_SIMPLE
)

# 5. 绘制轮廓
cv2.drawContours(
    image_np,
    contours,
    contourIdx=-1,
    color=(0, 0, 255),
    thickness=2
)
contour_image = image_np.copy()
for i, cnt in enumerate(contours):
    if hierarchy[0][i][3] != -1:
        cv2.drawContours(contour_image, [cnt], -1, (0, 255, 0), 2)

# 7. 图片输出
cv2.imshow('contour_image', contour_image)
cv2.imwrite('hexagram.jpg', contour_image)
cv2.waitKey(0)